package com.congee02.springframework.beans.factory.support;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.congee02.springframework.beans.BeansException;
import com.congee02.springframework.beans.DisposableBean;
import com.congee02.springframework.beans.PropertyValue;
import com.congee02.springframework.beans.PropertyValues;
import com.congee02.springframework.beans.factory.*;
import com.congee02.springframework.beans.factory.config.AutowireCapableBeanFactory;
import com.congee02.springframework.beans.factory.config.BeanDefinition;
import com.congee02.springframework.beans.factory.config.BeanPostProcessor;
import com.congee02.springframework.beans.factory.config.BeanReference;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;


/**
 * 继承于模板类，提供了 createBean 的实现
 */
@Slf4j
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory  {

    private InstantiationStrategy instantiationStrategy = new JDKInstantiationStrategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object... args) throws BeansException {
        Object bean;
        try {
            // 1. 实例化
            bean = createBeanInstance(beanDefinition, beanName, args);
            // 2. 依赖注入
            applyPropertyValues(beanName, bean, beanDefinition);
            // 3. BeanPostProcessor 和 初始化
            bean = initializeBean(beanName, bean, beanDefinition);
        } catch (Exception e) {
            throw new BeansException("Instantiation of Bean failed", e);
        }

        // 注册为可销毁的 bean
        registerDisposableBeanIfNecessary(beanName, bean, beanDefinition);

        // 单例 bean 加入到 singletonObjects
        if (beanDefinition.isSingleton()) {
            addSingleton(beanName, bean);
        }

        return bean;
    }

    protected void registerDisposableBeanIfNecessary(String beanName, Object bean, BeanDefinition beanDefinition) {
        if (! beanDefinition.isSingleton()) {
            return;
        }
        if (bean instanceof DisposableBean || StrUtil.isNotEmpty(beanDefinition.getDestroyMethodName())) {
            registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, beanDefinition));
        }
    }

    @SuppressWarnings("rawtypes")
    protected Object createBeanInstance(BeanDefinition beanDefinition, String beanName, Object... args) {

        log.debug("尝试实例化 bean beanDefinition: {}, beanName: {}, args: {}", beanDefinition, beanName, Arrays.toString(args));

        Constructor constructorToUse = null;
        Class<?> beanClazz = beanDefinition.getBeanClazz();
        Constructor<?>[] declaredConstructors = beanClazz.getDeclaredConstructors();
        for (Constructor ctor : declaredConstructors) {
            if (null != args && ctor.getParameterTypes().length == args.length) {
                constructorToUse = ctor;
                break;
            }
        }

        Object instance = instantiationStrategy.instantiate(beanDefinition, beanName, constructorToUse, args);
        log.debug("实例化完成: {}", instance);

        return instance;
    }

    protected void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
        try {
            PropertyValues propertyValues = beanDefinition.getPropertyValues();
            for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
                String name = propertyValue.getName();
                Object value = propertyValue.getValue();

                if (value instanceof BeanReference beanReference) {
                    value = getBean(beanReference.getBeanName());
                }

                Class<?> beanClass = bean.getClass();
                Field field = beanClass.getDeclaredField(name);
                field.setAccessible(true);
                field.set(bean, value);
            }
        } catch (Exception e) {
            throw new BeansException("Error setting property values: " + beanName, e);
        }
    }


    public InstantiationStrategy getInstantiationStrategy() {
        return instantiationStrategy;
    }

    public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
        this.instantiationStrategy = instantiationStrategy;
    }

    private Object initializeBean(String beanName, Object bean, BeanDefinition beanDefinition) {
        // 1. 执行 BeanPostProcessor Before 处理
        Object wrappedBean = applyBeanPostProcessorsBeforeInitialization(bean, beanName);

        // 2. 初始化
        try {
            invokeInitMethods(beanName, bean, beanDefinition);
        } catch (Exception e) {
            throw new BeansException("Invocation of init method of bean[" + beanName + "] failed", e);
        }

        // 3. 执行 BeanPostProcessor After 处理
        wrappedBean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
        return wrappedBean;
    }

    private void invokeInitMethods(String beanName, Object wrappedBean, BeanDefinition beanDefinition) throws Exception {

        // 感知方法调用
        if (wrappedBean instanceof Aware) {
            if (wrappedBean instanceof BeanFactoryAware beanFactoryAware) {
                beanFactoryAware.setBeanFactory(this);
            }
            if (wrappedBean instanceof BeanClassLoaderAware beanClassLoaderAware) {
                beanClassLoaderAware.setBeanClassLoader(getBeanClassLoader());
            }
            if (wrappedBean instanceof BeanNameAware beanNameAware) {
                beanNameAware.setBeanName(beanName);
            }
        }

        // 1. 实现接口 InitializingBean
        if (wrappedBean instanceof InitializingBean initializingBean) {
            initializingBean.afterPropertiesSet();
            return;
        }

        // 2. 配置信息 init-method
        String initMethodName = beanDefinition.getInitMethodName();
        if (StrUtil.isNotEmpty(initMethodName)) {
            Method initMethod = beanDefinition.getBeanClazz().getMethod(initMethodName);
            if (null == initMethod) {
                throw new BeansException("Could not find an init method named '" + initMethodName + "' on bean with name '" + beanName + "'");
            }
            initMethod.invoke(wrappedBean);
        }
    }

    @Override
    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;
        log.debug("执行 postProcessBeforeInitialization 前: existingBean: {}, beanName: {}", existingBean, beanName);
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessBeforeInitialization(result, beanName);
            if (null == current) return result;
            result = current;
        }
        log.debug("执行 postProcessBeforeInitialization 后: result: {}", result);
        return result;
    }

    @Override
    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;
        log.debug("执行 postProcessAfterInitialization 前: existingBean: {}, beanName: {}", existingBean, beanName);
        for (BeanPostProcessor processor : getBeanPostProcessors()) {
            Object current = processor.postProcessAfterInitialization(result, beanName);
            if (null == current) return result;
            result = current;
        }
        log.debug("执行 postProcessAfterInitialization 后: result: {}", result);
        return result;
    }
}
